package grupobbva.pe.operhc.util;

import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

public class CifraRSA {
		
	public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException, InvalidKeySpecException {
		
		BigInteger m = new BigInteger("9592302915668374591574941692139895848000754093203642725640118138745406111818348609338268189634169147832955580073749592851591652411601200275199607319050229");
		BigInteger e = new BigInteger("65537");
		
		RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
	    KeyFactory fact = KeyFactory.getInstance("RSA");
	    PublicKey llavePublica = fact.generatePublic(keySpec);
	    Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.ENCRYPT_MODE, llavePublica);
		String encriptar = "codUsu=P121427&tipDoc=E&numDoc=000032819&codFam=TC";
		byte[] cipherData = cipher.doFinal(encriptar.getBytes());
		System.out.println("CipherData: " + cipherData);
		System.out.println("CipherData (Length): " + cipherData.length);
		for (Byte b : cipherData) {
			System.out.print(b + ",");			
		}
		System.out.println();
		String hexa = bytesToHex(cipherData);
		System.out.println(new String(cipherData));
		System.out.println("La clave cifrada en hexa es: " + hexa);
	}
	
	final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
	
	public static String bytesToHex(byte[] bytes) {
	    char[] hexChars = new char[bytes.length * 2];
	    for ( int j = 0; j < bytes.length; j++ ) {
	        int v = bytes[j] & 0xFF;
	        hexChars[j * 2] = hexArray[v >>> 4];
	        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
	    }
	    return new String(hexChars);
	}
	
	

}
